package ld.oauth.blog.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ld.oauth.blog.model.po.user.SysUser;
import ld.oauth.blog.service.user.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获取网关转发过来的请求头中保存的明文的token值
 */
@Component
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {


    @Autowired
    private SysUserService sysUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authToken = request.getHeader("auth-token");
        if(StringUtils.isNoneBlank(authToken)){
            log.info("从网关拿到的token值为={}",authToken);
            //解析token
            String jsonString = new String(Base64Utils.decodeFromString(authToken));
            JSONObject jsonObject = JSON.parseObject(jsonString);

            String username = (String)jsonObject.get("principal");
            SysUser sysUser = sysUserService.findByName(username);
            Object details = jsonObject.get("details");
            jsonObject.getJSONArray("authorities").toArray();
            //拿到以逗号分隔的权限标识
            String authorities = ArrayUtils.toString(jsonObject.getJSONArray("authorities").toArray());
            List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
            //自己构建一个authentication对象 然后springsecutity就会自动进行权限判断，比如一些接口的
            //参数说明 名称  密码 权限集合
            UsernamePasswordAuthenticationToken authenticationToken
                    = new UsernamePasswordAuthenticationToken(sysUser,null,grantedAuthorityList);
            authenticationToken.setDetails(details);
            //将对象传给安全上下文 对应就会自动进行权限判断 同时也可以获取对象信息
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
